<template>
  <el-container direction="vertical">
    <!-- 头部区域 -->
    <el-header>
      <span class="header-title" @click="redirectHome">BMS管理系统</span>
      <button type="button" class="switch-btn" v-if="switchBtn" @click="switchNav">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <!-- 面包屑导航栏 移动端不展示 -->
      <el-breadcrumb separator="/" style="display: inline-block;color: #fff;" v-if="switchBtn">
        <template v-for="item in breadCrumbList">
          <el-breadcrumb-item :key="item.name" :to="{ path: item.path }">{{ item.name }}</el-breadcrumb-item>
        </template>
      </el-breadcrumb>
      <el-dropdown class="userinfo-inner" trigger="click" style="">
        <span class="el-dropdown-link">欢迎您，{{ sysUserName }}</span>
        <el-dropdown-menu>
          <el-dropdown-item icon="el-icon-message">站内信</el-dropdown-item>
          <el-dropdown-item icon="el-icon-user">个人中心</el-dropdown-item>
          <el-dropdown-item icon="el-icon-switch-button" divided @click.native="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-header>
    <el-container>
      <!-- 左侧菜单栏 -->
      <el-aside :width="asideWidth" style="transition: width .2s">
        <el-menu :default-active="$route.path" class="el-menu-vertical-demo" background-color="#333" text-color="#fff"
          active-text-color="#ffd04b" @open="handleOpen" @close="handleClose" :collapse="isCollapse" :unique-opened="true">
          <!-- 注释以下代码 用户头像区域 -->
          <!--
          <li class="user-item" :style="{height:(!isCollapse?'120px':'48px')}">
            <div style="display:flex;justify-content:center;">
              <img :src="userImg" alt="用户头像" style="display:block;border-radius:50%;margin-top:3px;" :width="!isCollapse?70:48" :height="!isCollapse?70:48" />
            </div>
            <div class="user-info" v-show="!isCollapse">
                <span>系统管理员 / {{sysUserName}}</span>
            </div>
          </li>
          -->
          <template v-for="item in sideNavList">
            <router-link menu-trigger="click" :key="item.indexTag" :to="item.link" v-if="item.children.length === 0">
              <el-menu-item :index="item.link" class="is-active">
                <i :class="item.icon"></i>
                <span slot="title">{{ item.name }}</span>
              </el-menu-item>
            </router-link>
            <el-submenu :key="item.indexTag" :index="item.indexTag" v-if="item.children.length !== 0">
              <template slot="title">
                <i :class="item.icon"></i>
                <span slot="title">{{ item.name }}</span>
              </template>
              <template v-for="subItem in item.children">
                <router-link :key="subItem.indexTag" :to="subItem.link" v-if="subItem.children.length === 0">
                  <el-menu-item :index="subItem.link">
                    <i :class="subItem.icon"></i>
                    <span slot="title">{{ subItem.name }}</span>
                  </el-menu-item>
                </router-link>
                <el-submenu :key="subItem.indexTag" :index="subItem.indexTag" v-if="subItem.children && subItem.children.length > 0">
                  <template slot="title">
                    <i :class="subItem.icon"></i>
                    <span slot="title">{{ subItem.name }}</span>
                  </template>
                  <router-link v-for="subSubItem in subItem.children" :key="subSubItem.indexTag" :to="subSubItem.link">
                    <el-menu-item :index="subSubItem.link">
                      <i :class="subSubItem.icon"></i>
                      <span slot="title">{{ subSubItem.name }}</span>
                    </el-menu-item>
                  </router-link>
                </el-submenu>
              </template>
            </el-submenu>
          </template>
        </el-menu>
      </el-aside>
      <!-- 右侧router-link跳转的页面 -->
      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      sysUserName: '',
      isCollapse: false,
      switchBtn: true,
      // 侧边栏菜单宽度（随窗口大小变化）
      asideWidth: '200px',
      // 侧边栏菜单
      sideNavList: [],
      // 面包屑导航文字
      breadCrumbList: [],
      userImg: require('../../assets/img/user/userImg2.jpg')
    }
  },
  mounted () {
    // MOCK数据
    /**
    let sideNavList = [
      {name: '仪表盘', icon: 'el-icon-s-platform', link: '/Dashboard', indexTag: '1', children: []},
      {name: '主数据维护', icon: 'el-icon-news', link: '', indexTag: '2', children: [{name: '品牌', link: '/Brand', icon: 'el-icon-news', indexTag: '2-1', children: []}, {name: '车系', link: '/LineChart', icon: 'el-icon-news', indexTag: '2-2', children: []}, {name: '车型', link: '/Pie', icon: 'el-icon-news', indexTag: '2-3', children: []}]},
      {name: '系统管理', icon: 'el-icon-setting', link: '', indexTag: '3', children: [{name: '组织', link: '/Org', icon: 'el-icon-s-home', indexTag: '3-1', children: []}, {name: '部门', link: '/Demo', icon: 'el-icon-s-home', indexTag: '3-2', children: []}, {name: '人员', link: '/User', icon: 'el-icon-user', indexTag: '3-3', children: []}, {name: '角色', link: '/Forms', icon: 'el-icon-user-solid', indexTag: '3-4', children: []}, {name: '菜单', link: '/Menu', icon: 'el-icon-menu', indexTag: '3-5', children: []}, {name: '字典', link: '', icon: 'el-icon-notebook-1', indexTag: '3-6', children: [{name: '目录', link: '/DictCategory', icon: 'el-icon-notebook-2', indexTag: '3-6-1', children: []}, {name: '字典项', link: '/DictItem', icon: 'el-icon-notebook-2', indexTag: '3-6-2', children: []}]}]},
      {name: '表格管理', icon: 'el-icon-menu', link: '', indexTag: '4', children: [{name: '员工表', link: '/EmployeeTable', icon: 'el-icon-menu', indexTag: '4-1', children: []}, {name: '教师表', link: '/TeacherTable', icon: 'el-icon-menu', indexTag: '4-2', children: []}, {name: '待办项表', link: '/TodoTable', icon: 'el-icon-menu', indexTag: '4-3', children: []}]},
      {name: '一级菜单', icon: 'el-icon-document', link: '', indexTag: '5', children: [{name: '二级菜单1', link: '', icon: 'el-icon-menu', indexTag: '5-1', children: [{name: '三级菜单1', link: '/Foo', icon: 'el-icon-menu', indexTag: '5-1-1', children: []}]}, {name: 'Baz', link: '/Baz', icon: 'el-icon-menu', indexTag: '5-2', children: []}]},
      {name: '图表展示', icon: 'el-icon-news', link: '', indexTag: '6', children: [{name: '柱状图', link: '/Bar', icon: 'el-icon-news', indexTag: '6-1', children: []}, {name: '折线图', link: '/LineChart', icon: 'el-icon-news', indexTag: '6-2', children: []}, {name: '饼图', link: '/Pie', icon: 'el-icon-news', indexTag: '6-3', children: []}]}
    ]
    this.sideNavList = sideNavList
    */

    // 测试REPAIR FEIGN
    // this.$apis.getCommonFeign().then(res => {
    //   console.log(res)
    // }).catch(err => {
    //   console.log(err)
    //   this.loading = false
    //   this.$notify.error({
    //     title: '错误',
    //     message: '请求异常'
    //   })
    // })

    // 优先从缓存中取菜单
    let menu = localStorage.getItem('menu')
    let permission = localStorage.getItem('permission')
    if (menu && permission) {
      this.sideNavList = JSON.parse(menu)
    } else {
      // 查询当前用户可见的系统资源
      this.$apis.queryAppData().then(res => {
        if (res && res.code === '200') {
          // console.log(res.result)
          this.sideNavList = res.result.menus

          // 如果需求是刷新后回到首页，才需要加上这段代码
          // this.$router.push({path: this.sideNavList[0].link})
          // this.breadCrumbList = this.findParent(this.sideNavList[0].link, this.sideNavList)

          // 缓存资源
          localStorage.setItem('menu', JSON.stringify(res.result.menus))
          localStorage.setItem('permission', JSON.stringify(res.result.permissions))
        } else {
          console.log(res)
          this.$notify.error({
            title: '错误',
            message: res.message
          })
          this.loading = false
        }
      }).catch(err => {
        console.log(err)
        this.loading = false
        this.$notify.error({
          title: '错误',
          message: '请求异常'
        })
      })
    }

    // 填充面包屑导航
    this.breadCrumbList = this.findParent(this.$route.path, this.sideNavList)

    // 填充右上角用户名称
    let user = localStorage.getItem('user')
    user = JSON.parse(user)
    // console.log('user==========', user)
    if (user) {
      this.sysUserName = user.username
    }

    this.screenWidth = document.body.clientWidth
    if (this.screenWidth < 500) {
      this.isCollapse = true
      this.switchBtn = false
    } else {
      this.isCollapse = false
      this.switchBtn = true
    }

    // 页面加载获取当前窗口宽度
    window.onresize = () => {
      return (() => {
        this.screenWidth = document.body.clientWidth
        if (this.screenWidth < 700) {
          this.isCollapse = true
          this.switchBtn = false
        } else {
          this.isCollapse = false
          this.switchBtn = true
        }
      })()
    }
  },
  watch: {
    isCollapse (val) {
      if (val) {
        this.asideWidth = '64px'
      } else {
        this.asideWidth = '200px'
      }
    },
    // 监听路由变化来改变面包屑导航文字
    '$route': function (val) {
      let param = this.$route.path
      console.log(val)

      // 面包屑导航
      let arr = this.findParent(param, this.sideNavList)
      this.breadCrumbList = arr

      // 判断用户输入的菜单是否有权限访问, 无权限arr=false
      if (!arr && val.path !== '/404') {
        this.$notify.error({
          title: '错误',
          message: '您没有权限访问此菜单'
        })
        this.redirectHome()
      }
    }
  },
  methods: {
    // 重定向跳转到首页
    redirectHome () {
      this.$router.push({path: this.sideNavList[0].link})
    },

    // nav切换开关
    switchNav () {
      this.isCollapse = !this.isCollapse
    },

    handleOpen (key, keyPath) {
      // console.log(key, keyPath)
    },

    handleClose (key, keyPath) {
      // console.log(key, keyPath)
    },

    // 注销
    logout () {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        customClass: 'message-confirm'
      }).then(() => {
        // 调用后端接口注销
        this.$apis.logout({ }).then(res => {
          if (res && res.code === '200') {
            localStorage.removeItem('user')
            localStorage.removeItem('menu')
            this.$router.push('/Login')
            this.$notify({
              title: '成功',
              message: '已成功注销',
              type: 'success'
            })
          } else {
            console.log(res)
            let errorMsg = res.message ? res.message : '注销失败'
            this.$notify.error({
              title: '错误',
              message: errorMsg
            })
          }
        }).catch(err => {
          console.log(err)
          this.$notify.error({
            title: '错误',
            message: '注销失败'
          })
        })
      }).catch(() => {
        // 用户取消注销
      })
    },

    // 根据点击的菜单节点找到父节点组成
    findParent: function (id, list = [], result = []) {
      for (let i = 0; i < list.length; i += 1) {
        // console.log(`***${list[i].link}***`)
        const item = list[i]
        var obj = {
          name: item.name,
          path: item.link
        }
        if (item.link === id) {
          result.push(obj)
          if (result.length === 1) return result
          return true
        }
        // 如果存在下级节点，则继续遍历
        if (item.children) {
          // 预设本次是需要的节点并加入到最终结果result中
          result.push(obj)
          const find = this.findParent(id, item.children, result)
          // 如果不是false则表示找到了，直接return，结束递归
          if (find) return result
          // 到这里，意味着本次并不是需要的节点，则在result中移除
          result.pop()
        }
      }
      // 如果都走到这儿了，也就是本轮遍历children没找到，将此次标记为false
      return false
    }
  }
}
</script>

<style scoped>
  .el-container {
    height: 100vh;
  }
  .el-header {
    background-color: #333;
    color: #fff;
    line-height: 60px;
  }
  .header-title {
    display: inline-block;
    padding-right: 20px;
    cursor: pointer;
  }
  .el-aside {
    background-color: #333;
    color: #fff;
    height: 100%;
  }
  /* height需要减去header的高度 */
  .el-main {
    background: #fff;
    color: #333;
    padding: 0px;
    height: calc(100vh - 60px);
  }
  .el-menu {
    border-right: 1px solid #333;
  }
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
  }
  .switch-btn {
    position: relative;
    padding: 7px 10px 5px;
    margin-top: 8px;
    margin-right: 15px;
    margin-bottom: 8px;
    background-color: transparent;
    background-image: none;
    border: 1px solid #606266;
    border-radius: 4px;
    cursor: pointer;
  }
  .switch-btn .icon-bar {
    display: block;
    margin-bottom: 4px;
    width: 22px;
    height: 2px;
    border-radius: 1px;
    background-color: #fff;
  }
  .el-menu-item .is-active {
    background-color: #222 !important;
    color: #ffd04b;
  }
  .user-item {
    transition: height .2s;
    margin-top: 5px;
  }
  .user-info {
    margin: 10px 0 0 0;
    font-size: 15px;
    height: 30px;
    text-align: center;
  }
  .el-submenu__icon-arrow {
    position: absolute;
    top: 50%;
    right: 0;
  }
  /* 隐藏滚动条 */
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    color: transparent;
  }
  .userinfo-inner {
    display: inline-block;
    float: right;
    color: #fff;
    font-size: 15px;
    font-weight: 400;
    margin-right: 10px;
  }
</style>

<style>
  /* 此处style不能加scope */
  .message-confirm {
    width: 320px;
  }
</style>
